<template>
  <div @keyup.enter="reGetData()">
    <el-form class="query-table-form" :inline="true">
      <el-form-item>
        <el-input v-model="params.customer_name" placeholder="主体名称查询" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="params.corp_name" placeholder="负责人查询" :clearable="true"></el-input>
      </el-form-item>
      <el-form-item>
        <select-address
          v-model="params.address_code"
          clearable
          placeholder="地址查询"
          :auto-top="true"
          @change="reGetData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="reGetData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportExcel('项目调查（调查中）')"
        >
          导出
        </el-button>
      </el-form-item>
    </el-form>
    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData">
      <template v-slot:address="scope">
        <div class="text-truncate" :title="scope.row.address">{{ scope.row.address }}</div>
      </template>
      <template v-slot:itemStatus="scope">
        <span class="badge" :class="`badge-${scope.row.itemStatusStyle}`">
          {{ scope.row.itemStatusLabel }}
        </span>
      </template>
      <template v-slot:name="scope">
        <el-popover placement="top-start" title="项目经理" trigger="hover">
          <div>
            <div>{{ `A角： ${scope.row.res_a_name || '-'}；` }}</div>
            <div class="mb-2">{{ `电话： ${scope.row.res_a_phone || '-'}` }}</div>
            <div>{{ `B角： ${scope.row.res_b_name || '-'}；` }}</div>
            <div>{{ `电话： ${scope.row.res_b_phone || '-'}` }}</div>
          </div>
          <div slot="reference">
            <div class="status-label badge-info text-left w-100">
              <div>A角:{{ scope.row.res_a_name }}</div>
              <div>B角:{{ scope.row.res_b_name }}</div>
            </div>
          </div>
        </el-popover>
      </template>
      <template v-slot:tags="scope">
        <el-popover placement="top-start" title="附件状态" trigger="hover">
          <div v-for="(tag, index) in scope.row.tags" :key="index">
            <div>
              <i class="fa fa-fw mr-1" :class="tag.icon"></i>
              <span>{{ tag.tag }}</span>
            </div>
          </div>
          <span slot="reference" class="badge" :class="`badge-${scope.row.tagStyle}`">
            {{ scope.row.tagLabel }}
          </span>
        </el-popover>
      </template>
    </c-table>
    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="reGetData"
      ></el-pagination>
    </div>

    <approve-dialog
      :visible.sync="editVisible"
      :query-id="editRow.customer_related_id"
      ref="approve"
      @success="reGetData()"
      @attach-success="reGetData()"
    ></approve-dialog>

    <attach-dialog
      :visible.sync="attachVisible"
      :related-id="attachId"
      @success="handleAttachSuccess()"
    ></attach-dialog>

    <view-dialog :visible.sync="viewVisible" :related-data="viewRow"></view-dialog>
  </div>
</template>

<script>
import { getTagsStatus } from '@/credit/views/city/self/normal/invest/attach'
import { enumGuatype, enumProjectResStatus, enumProcessStatus } from '@/credit/plugins/enumTown'
import { baseTableColumns } from '@/credit/views/county/unionProvince/Approve'
import baseMixins from '@/bigcredit/views/self/fast/todoMixins'

import SelectAddress from '@/components/select/SelectAddress'
import ApproveDialog from '@/bigcredit/views/self/fast/invest/components/MainDialog'
import AttachDialog from '@/credit/views/city/self/normal/invest/AttachDialog'
import ViewDialog from '@/bigcredit/views/self/fast/invest/components/ViewDialog'

export default {
  components: {
    SelectAddress,
    ApproveDialog,
    AttachDialog,
    ViewDialog,
  },
  mixins: [baseMixins],
  data() {
    return {
      enumGuatype,
      enumProjectResStatus,
      enumProcessStatus,
      order: {
        approved_date: 'desc',
      },
      params: {
        index: 1,
        size: 15,
        address_code: '',
        customer_name: '',
        corp_name: '',
        'task_type.in': '5,6',
      },

      tableData: [],
      tableColumns: [
        ...baseTableColumns,
        { attrs: { label: '建议金额(万元)', prop: 'approved_funds', align: 'center' } },
        { attrs: { label: '立项时间', prop: 'itemDate', width: 140 } },
        { attrs: { label: '担保机构', prop: 'service_name', align: 'center', minWidth: '110px' } },
        {
          attrs: { label: '合作银行', prop: 'bank_name', align: 'center' },
          process: v => v || '-',
        },
        { attrs: { label: '审批模式', prop: 'processLabel', width: 80, align: 'center' } },
        { attrs: { label: '项目经理', prop: 'resName', width: 100 }, slot: 'name' },
        {
          attrs: { label: '项目状态', prop: 'itemStatusLabel', align: 'center' },
          slot: 'itemStatus',
        },
        { attrs: { label: '附件状态', align: 'center' }, slot: 'tags' },
        {
          attrs: { label: '操作', align: 'center', minWidth: 150 },
          operations: [
            {
              content: '项目审查',
              icon: 'fa fa-gavel',
              event: this.handleApprove,
              ifRender: row => row.editEnable,
            },
            { content: '上传附件', icon: 'fa fa-clipboard', event: this.handleAttach },
            { content: '查看', icon: 'fa fa-search', event: this.handleView },
          ],
        },
      ],

      editRow: {},
      editVisible: false,

      attachId: '',
      attachVisible: false,

      viewRow: {},
      viewVisible: false,
    }
  },
  computed: {},
  watch: {},
  mounted() {},
  created() {
    this.reGetData()
  },
  methods: {
    async reGetData(index = 1) {
      this.getData(index).then(() => this.getAttach())
      this.$store.dispatch('getTaskCountBusSelfFast')
    },
    getAttach() {
      const relatedIds = this.tableData.map(item => item.customer_related_id).join(',')
      if (!relatedIds) return
      Promise.all([
        this.$api.getData({
          table: 'datum_customer_attachment',
          params: {
            'customer_related_id.in': relatedIds,
          },
        }),
      ])
        .then(([attachRes]) => {
          const attachs = attachRes.data || []
          const attachObj = {}
          for (const attach of attachs) {
            const relatedId = attach.customer_related_id
            if (!attachObj[relatedId]) {
              attachObj[relatedId] = []
            }
            attachObj[relatedId].push(attach)
          }

          this.tableData = this.tableData.map(it => {
            const relatedId = it.customer_related_id
            const atts = attachObj[relatedId] || []

            let hasFinish = true
            it.tags = getTagsStatus(atts, it)
            it.tags = it.tags.map(tag => {
              if (!tag.finish) {
                hasFinish = false
              }
              return {
                ...tag,
                icon: tag.hasUpload
                  ? 'text-success fa-check'
                  : tag.required
                  ? 'text-danger fa-times'
                  : 'fa-minus',
              }
            })
            it.tagStyle = hasFinish ? 'success' : 'danger'
            it.tagLabel = hasFinish ? '已完成' : '未完成'
            return it
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    dataAdapter(item) {
      item.guaType = enumGuatype[item.gua_type] || '-'

      item.resName = `A角: ${item.res_a_name} B角: ${item.res_b_name}`
      item.itemDate = this.$utils.dateFormat(item.item_date, this.dateFmt)

      const itemStatus = enumProjectResStatus[item.project_res_status] || {}
      item.itemStatusLabel = itemStatus.label
      item.itemStatusStyle = itemStatus.css
      item.processLabel = enumProcessStatus[+item.process_status] || ''

      item.editEnable = this.editButton(item)

      return item
    },
    editButton(_row) {
      return true // this.userId === _row.res_a
    },
    handleApprove(row) {
      this.editRow = { ...row }
      this.editVisible = true
    },
    handleAttach(row) {
      this.attachVisible = true
      this.attachId = row.customer_related_id
    },
    handleView(row) {
      this.viewRow = row
      this.viewVisible = true
    },
    handleAttachSuccess() {
      this.reGetData(this.params.index)
      if (this.$refs.approve) {
        this.$refs.approve.getData()
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.status-label {
  display: inline-block;
  padding: 0.25em 0.4em;
  font-size: 75%;
  font-weight: 700;
  line-height: 1;
  text-align: center;
  vertical-align: baseline;
  border-radius: 0.25rem;
  transition: color 0.15s;
}
</style>
